package cn.hn3l.dao.implement;

import cn.hn3l.dao.interfaces.DaoBooktype;
import cn.hn3l.model.Booktype;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by weiwei02 on 2016/8/29.
 */
public class DaoBooktypeImpl implements DaoBooktype {
    @Resource
    private JdbcTemplate jdbcTemplate;
    @Override
    public Booktype getBooktype(Long typeid) {
        String sql = "select * from tb_booktype where id = ?";
        RowMapper<Booktype> rowMapper = BeanPropertyRowMapper.newInstance(Booktype.class);
        List<Booktype> list = jdbcTemplate.query(sql, rowMapper,typeid);
        return list.get(0);
    }

    @Override
    public List<Booktype> getAllBooktype() {
        String sql = "select * from tb_booktype";
        RowMapper<Booktype> rowMapper = BeanPropertyRowMapper.newInstance(Booktype.class);
        List<Booktype> list = jdbcTemplate.query(sql, rowMapper);
        return list;
    }

    /**根据value新增加一个图书类型*/
    @Override
    public boolean addNewBookType(String value) {
        String sql = "insert into bookmanger.tb_booktype(typename) values (?)";
        if (jdbcTemplate.update(sql,value) > 0){
            return true;
        }
        return false;
    }

    @Override
    public boolean deleteBookType(String value) {
        String sql = "DELETE FROM bookmanger.tb_booktype WHERE bookmanger.tb_booktype.typename = ?";
        if (jdbcTemplate.update(sql,value) > 0){
            return true;
        }
        return false;
    }

    @Override
    public boolean alterNameFromBooktype(String value1, String value2) {
        String sql = "UPDATE bookmanger.tb_booktype SET bookmanger.tb_booktype.typename = ?" +
                " WHERE bookmanger.tb_booktype.typename = ? ";
        if (jdbcTemplate.update(sql, value2, value1) > 0){
            return true;
        }
        return false;
    }

    @Override
    public int findIdByName(String value) {
        String sql = "SELECT id FROM bookmanger.tb_booktype WHERE bookmanger.tb_booktype.typename = ?";
        return jdbcTemplate.queryForObject(sql,Integer.class,value);
    }

}
